using OpenTK;

namespace ColladaDotNet.OpenTKMapping
{
	public class PerspectiveCameraOptics:CameraOptics
	{
		private double? xfov;

		private double? yfov;

		private double aspect_ratio=1;



		public override Matrix4d Projection
		{
			get
			{
				return GetProjection(aspect_ratio);
			}
		}

		public override Matrix4d GetProjection(double aspect)
		{
			double yf;
			if (yfov == null)
				yf = xfov.Value / aspect;
			else
				yf = yfov.Value;
			var m = Matrix4.CreatePerspectiveFieldOfView(MathHelper.DegreesToRadians((float)yf), (float)aspect, (float)zNear, (float)zFar);
			return new Matrix4d(
					m.M11, m.M12, m.M13, m.M14, m.M21, m.M22, m.M23, m.M24,
					m.M31, m.M32, m.M33, m.M34, m.M41, m.M42, m.M43, m.M44);
		}

		public double YFov
		{
			get
			{
				if (yfov == null)
					return xfov.Value * aspect_ratio;
				return yfov.Value;
			}
		}
		public double XFov
		{
			get
			{
				if (xfov == null)
					return yfov.Value / aspect_ratio;
				return xfov.Value;
			}
		}


		internal override void Load(cameraOptics colladaData)
		{
			base.Load(colladaData);
			var tech = (cameraOpticsTechnique_commonPerspective)Collada.technique_common.Item;
			zNear = tech.znear.Value;
			zFar = tech.zfar.Value;
			for (int i = 0; i < tech.Items.Length; i++)
			{
				var item = tech.Items[i];
				var t = tech.ItemsElementName[i];
				switch (t)
				{
					case ItemsChoiceType1.xfov:
						xfov = ((TargetableFloat)item).Value;
						break;
					case ItemsChoiceType1.yfov:
						yfov = ((TargetableFloat)item).Value;
						break;
					case ItemsChoiceType1.aspect_ratio:
						aspect_ratio = ((TargetableFloat)item).Value;
						break;
				}
			}
		}

	}
}